import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";

// a little function to help us with reordering the result
const reorder = (list, startIndex, endIndex) => {
	const result = Array.from(list);
	const [removed] = result.splice(startIndex, 1);
	result.splice(endIndex, 0, removed);

	return result;
};


const getItemStyle = (isDragging, draggableStyle) => ({
	// some basic styles to make the items look a bit nicer
	userSelect: "none",
	// change background colour if dragging
	background: isDragging ? "#F8FAFF" : "none",
	// styles we need to apply on draggables
	...draggableStyle
});

const getListStyle = isDraggingOver => ({
	 background: isDraggingOver ? "#EBF4FF" : "none",
});


const DragComp = (props) => {
	const { items, dragKey = 'id', renderDragItem, handleDragEnd } = props;
	const onDragEnd = result => {
		// dropped outside the list
		if (!result.destination) {
			return;
		}
		const item = reorder(
			items,
			result.source.index,
			result.destination.index
		);
		handleDragEnd(item)
	}

	return (
		<DragDropContext onDragEnd={onDragEnd}>
			<Droppable droppableId="droppable">
				{(provided, snapshot) => (
					<div
						{...provided.droppableProps}
						ref={provided.innerRef}
						style={getListStyle(snapshot.isDraggingOver)}
					>
						{items.map((item, index) => (
							<Draggable key={item[dragKey]} draggableId={item[dragKey] + ''} index={index}>
								{(provided, snapshot) => (
									<div
										ref={provided.innerRef}
										{...provided.draggableProps}
										{...provided.dragHandleProps}
										style={getItemStyle(
											snapshot.isDragging,
											provided.draggableProps.style
										)}
									>
										{renderDragItem(item)}
									</div>
								)}
							</Draggable>
						))}
						{provided.placeholder}
					</div>
				)}
			</Droppable>
		</DragDropContext>
	);
}

export default DragComp;
// Put the thing into the DOM!
